const app = getApp();
const WxParse = require('../wxParse/wxParse')
import API from "../api/cloud";
import {
  getCreditShopList,
  getShopList,
  credit,
  getProductByID,
  getOrderLists,
  getExpresss,
  setOrder,
  getProductList,
  getHotShopList,
  getStickyShopList,
  getMiniShopList,
  getMiniShopCates,
  getCouponsList,
  getCoupon
} from "../api/shop";

/**
 * 获取商品列表
 */

const getCreditShopLists = function (args) {
  getCreditShopList(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
          showloadmore: false
        })
      }
      if (this.data.isPull) {
        args.products = [].concat(this.data.products, res)
        args.shoppage = this.data.shoppage + 1
      } else if (this.data.isBottom) {
        args.products = [].concat(this.data.products, res)
        args.shoppage = this.data.shoppage + 1
      } else {
        args.products = res
        args.shoppage = this.data.shoppage + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      args.showSkeleton = false
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}


const getShopLists = function (args) {
  getShopList(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
          showloadmore: false
        })
      }
      if (this.data.isPull) {
        args.products = [].concat(this.data.products, res)
        args.shoppage = this.data.shoppage + 1
      } else if (this.data.isBottom) {
        args.products = [].concat(this.data.products, res)
        args.shoppage = this.data.shoppage + 1
      } else {
        args.products = res
        args.shoppage = this.data.shoppage + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      args.showSkeleton = false
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}


const getHotShopLists = function (args) {
  getHotShopList(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          isLastHotPage: true,
          loadtext: '到底啦',
          showloadmore: false
        })
      }
      if (this.data.isPull) {
        args.hotProducts = [].concat(this.data.hotProducts, res)
        args.shopHotpage = this.data.shopHotpage + 1
      } else if (this.data.isBottom) {
        args.hotProducts = [].concat(this.data.hotProducts, res)
        args.shopHotpage = this.data.shopHotpage + 1
      } else {
        args.hotProducts = res
        args.shopHotpage = this.data.shopHotpage + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      args.showSkeleton = false
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}


const getStickyShopLists = function (args) {
  getStickyShopList(args).then(res => {
      let args = {}
      args.Sticky = res
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      wx.stopPullDownRefresh()
    })
}



const getproductDetail = function () {
  let id = this.data.id
  getProductByID(id).then(res => {
      //console.log(res)
      let args = {}
      let current = getCurrentPages()
      if (current.length === 1) {
        args.isShare = true
      }
      args.showloading = false
      WxParse.wxParse('article', 'html', res.content.rendered, this, 5)
      args.isPull = false
      //args.isShow = true
      args.detail = res
      args.isLike = res.islike;
      args.isfav = res.isfav;
      if (res.comments != 0) {
        args.isComments = true
        this.getPostsComments({
          id: this.data.id,
          page: this.data.page,
          order: 'desc'
        })
      }
      if (res.isvote) {
        let count = 0
        for (let i = 0; i < res.vote.options.length; i++) {
          count += res.vote.options[i].count;
        }
        args.count = count
      }
      args.showSkeleton = false
      //  this.getRelatedPosts()
      // this.getDetailAds()
      this.setData(args)
      // 阅读记录缓存数据
      let record = {}
      let title = {}
      let excerpt = {}
      let categories = []
      let cate = {}
      let meta = {}
      record.id = res.id
      record.type = res.type
      record.date = res.date
      title.rendered = res.title.rendered
      excerpt.rendered = res.excerpt.rendered
      meta = res.meta
      record.meta = meta
      record.comments = res.comments
      record.favs = res.favs
      record.likes = res.likes
      record.title = title
      record.excerpt = excerpt
      record.categories = categories
      // 调用 API 从本地缓存中获取阅读记录并记录
      let logs = wx.getStorageSync('readLogs') || []
      let readsave = true
      // 过滤重复值
      if (logs.length > 0) {
        for (let i = 0; i < logs.length; i++) {
          if (logs[i].id == res.id) {
            readsave = false
            break;
          }
        }
      }
      if (readsave) {
        logs.unshift(record)
      }
      // 如果超过指定数量
      if (logs.length > 9) {
        logs.pop(); // 去除最后一个
      }
      wx.setStorageSync('readLogs', logs)
      //阅读记录缓存结束
      wx.stopPullDownRefresh()
    })
    .catch(err => {
      if (this.data.isPull) {
        this.setData({
          isPull: false
        })
        wx.stopPullDownRefresh()
      }
      console.log(err)
    })
}

const creditPay = function () {
  let that = this;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return;
  }
  let address = that.data.addressList;
  if (!address) {
    wx.showToast({
      title: '请设置收货地址',
    })
    return
  }
  let args = {
    id: that.data.detail.id,
    type: 'credit',
    count: that.data.cart_num,
    model: that.data.model.join(","),
    message: that.data.message,
    address: '地址：' + address.address.province + address.address.city + address.address.district + address.detail + '--' + '联系人：' + address.real_name + "--" + "电话号码：" + address.phone,
  }
  credit(args).then(res => {
    console.log(res);
    if (res.status == 200) {
      wx.redirectTo({
        url: '/pages/shop/exchanges',
      })
      wx.showToast({
        title: '交换成功',
      })
    }

  }).catch(err => {
    wx.showModal({
      title: '兑换失败',
      content: err.message,
      cancelText: '取消',
      confirmText: '确定',
      success(res) {
        if (res.cancel) {
          // 用户点击了取消属性的按钮，对应选择了'女'
          that.setData({
            userSex: 2
          })
        } else if (res.confirm) {
          // 用户点击了确定属性的按钮，对应选择了'男'
          that.setData({
            userSex: 1
          })
        }
      }
    })
  })

}



const getOrderList = function (data) {
  let args = [],
    that = this

  getOrderLists(data).then(res => {
      if (res.code == "error") {

      } else {
        if (res.orders.length < 10) {
          this.setData({
            isLastPage: true,
            loadtext: '到底啦',
          })
        }
        if (this.data.isBottom) {
          args.orderList = [].concat(this.data.orderList, res.orders)
          args.page = this.data.page + 1
          that.setData(args);
        } else {
          this.setData({
            page: this.data.page + 1,
            orderList: res.orders
          })
        }
      }
    })
    .catch(err => {})
}

const getExpress = function (id) {
  let that = this;
  let args = {
    num: id,
  }
  getExpresss(args).then(res => {
    this.setData({
      express: res.msg,
      context: that.data.context.concat(res.msg.context.map(function (item) {
        item.time = that.getDateTime(item.time * 1000, 'Y年M月D日 h:m:s');
        return item;
      }))
    })
  })

}


const getDateTime = function (number, format) {
  let time = new Date(number)
  let newArr = []
  let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
  newArr.push(time.getFullYear())
  newArr.push(this.formatNumber(time.getMonth() + 1))
  newArr.push(this.formatNumber(time.getDate()))

  newArr.push(this.formatNumber(time.getHours()))
  newArr.push(this.formatNumber(time.getMinutes()))
  newArr.push(this.formatNumber(time.getSeconds()))

  for (let i in newArr) {
    format = format.replace(formatArr[i], newArr[i])
  }
  return format;
}



const action = function (e) {
  let that = this;
  wx.showModal({
    title: '是否进行此操作',
    success: function (res) {
      if (res.confirm) {
        let id = e.currentTarget.id;
        let action = e.currentTarget.dataset.action;
        let status = e.currentTarget.dataset.status;
        let index = e.currentTarget.dataset.index;
        let args = {
          action: action,
          id: id,
          status: status
        }
        setOrder(args).then(res => {
          console.log(res);
          if (res.status == 200 && action == 'delete') {
            wx.showToast({
              title: '删除成功',
            })
            that.data.orderList.splice(index, 1);
            that.setData({
              orderList: that.data.orderList
            })
          }
          if (res.status == 200 && action == 'edit') {
            wx.showToast({
              title: '已确定收货',
            })
            that.data.orderList[index].status = 'received';
            that.setData({
              orderList: that.data.orderList
            })
          }
        })
      } else {

      }
    }
  })

}


/** 获取商品分类 */
const getMiniShopCategories = function (args) {
  getMiniShopCates(args).then(res => {
      let args = {}
      if (res.length != 0) {
        args.categoryMap = res;
      } else {
        args.categoryMap = [{
          name: '全部',
          id: 0
        }];
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
    })
}




/** 获取商品分类 */
const getCategories = function (args) {
  getProductList(args).then(res => {
      let args = {}
      if (res.length != 0) {
        args.categoryMap = res;
      } else {
        args.categoryMap = [{
          name: '全部',
          id: 0
        }];
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
    })
}


const getMiniShopLists = function (args) {
  getMiniShopList(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
          showloadmore: false
        })
      }
      if (this.data.isPull) {
        args.products = [].concat(this.data.products, res)
        args.shoppage = this.data.shoppage + 1
      } else if (this.data.isBottom) {
        args.products = [].concat(this.data.products, res)
        args.shoppage = this.data.shoppage + 1
      } else {
        args.products = res
        args.shoppage = this.data.shoppage + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      args.showSkeleton = false
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}


/** 获取商品分类 */
const getCouponsLists = function (args) {
  getCouponsList(args).then(res => {
      let args = {}
      if (res.length != 0) {
        args.couponsList = res;
        if(wx.getStorageSync('show')!==false)
        {
        args.show=true;
        }
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
    })
}

const getCoupons=function(e){
let cid=e.currentTarget.id;
  getCoupon({id:cid}).then(res=>{
  console.log(res);
  if(res.errcode==0){
    wx.showToast({
      title: '优惠券已领取',
    })
  }
  else if(res.errcode==109101){
    wx.showToast({
      title: '优惠券库存不足',
    })
  }
  else if(res.errcode==109102){
    wx.showToast({
      title: '优惠券还没过期',
    })
  }
  else if(res.errcode==109103){
    wx.showToast({
      title: '优惠券限领',
    })
  }
})
}


module.exports = function (obj) {
  obj.getCreditShopLists = getCreditShopLists;
  obj.getproductDetail = getproductDetail;
  obj.creditPay = creditPay;
  obj.getOrderList = getOrderList;
  obj.getDateTime = getDateTime;
  obj.getExpress = getExpress;
  obj.action = action;
  obj.getShopLists = getShopLists;
  obj.getCategories = getCategories;
  obj.getHotShopLists = getHotShopLists;
  obj.getMiniShopLists=getMiniShopLists;
  obj.getStickyShopLists = getStickyShopLists;
  obj.getMiniShopCategories=getMiniShopCategories;
  obj.getCouponsLists=getCouponsLists;
  obj.getCoupons=getCoupons;
}